package com.smcaiot.filesync.starter.app;

import com.smcaiot.filesync.starter.constants.HandlerType;
import com.smcaiot.filesync.starter.handler.SyncFinishHandler;
import com.smcaiot.filesync.starter.handler.impl.AbstractCompressPicHandler;
import com.smcaiot.filesync.starter.handler.impl.AbstractPullFileHandler;
import com.smcaiot.filesync.starter.handler.impl.AbstractPushFileHandler;
import com.smcaiot.filesync.starter.handler.impl.BaseHandler;
import com.smcaiot.filesync.starter.util.ReflectTool;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: cz
 * @Date: 2023/6/30
 * @Description:
 */
@Configuration
public class HandlerContext implements ApplicationContextAware {

    private Map<String, AbstractCompressPicHandler> compressPicHandlerMap;
    private Map<String, AbstractPushFileHandler> pushFileHandlerMap;
    private Map<String, AbstractPullFileHandler> pullFileHandlerMap;

    @Override
    public void setApplicationContext(ApplicationContext ctx) throws BeansException {
        compressPicHandlerMap = getHandlerClassMap(ctx, AbstractCompressPicHandler.class);
        pushFileHandlerMap = getHandlerClassMap(ctx, AbstractPushFileHandler.class);
        pullFileHandlerMap = getHandlerClassMap(ctx, AbstractPullFileHandler.class);
    }

    private <T> Map<String, T> getHandlerClassMap(ApplicationContext ctx, Class<T> handlerClass) {
        Map<String, T> classMap = new HashMap();
        ctx.getBeansOfType(handlerClass).values().forEach(handler -> {
            Class genericClz = ReflectTool.getGenericParameterClass(handler.getClass());
            classMap.put(genericClz.getSimpleName(), handler);
        });
        return classMap;
    }

    @Bean
    public Map<String, AbstractCompressPicHandler> compressPicHandlerMap() {
        return compressPicHandlerMap;
    }

    @Bean
    public Map<String, AbstractPushFileHandler> pushFileHandlerMap() {
        return pushFileHandlerMap;
    }

    @Bean
    public Map<String, AbstractPullFileHandler> pullFileHandlerMap() {
        return pullFileHandlerMap;
    }

    public BaseHandler getHandler(HandlerType handlerType, String clz) {
        switch (handlerType) {
            case compress:
                return compressPicHandlerMap.get(clz);
            case push:
                return pushFileHandlerMap.get(clz);
            case pull:
                return pullFileHandlerMap.get(clz);
            default:
                throw new RuntimeException("不支持的Handler类型");
        }
    }

}
